package com.example.urmsadmin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.urmsadmin.Util.*;
import com.example.urmsadmin.entity.SysUser;
import com.example.urmsadmin.service.SysUserRoleService;
import com.example.urmsadmin.service.SysUserService;
import com.example.urmsadmin.service.impl.SysUserServiceImpl;
import com.example.urmsadmin.vo.CommonResult;
import com.example.urmsadmin.vo.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.example.urmsadmin.Util.ValidatorUtil;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 用户信息表(SysUser)表控制层
 *
 * @author makejava
 * @since 2022-07-12 08:41:09
 */
@RestController
@Slf4j
@RequestMapping(value = "/sysUser")
public class SysUserController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private SysUserRoleService userRoleService;

    /**
     * @param userName 登录用户名
     * @param password 用户密码
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/login")
    public CommonResult<String> login(@RequestParam(value = "userName") String userName,
                                      @RequestParam(value = "password") String password) throws NoSuchAlgorithmException {
        log.info("执行了===>SysUserController中的login方法");
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        SysUser user = userService.getOne(wrapper);
        if (user != null) {
            String newPwd = SaltEncryption.saltEncryption(password, user.getSalt());
            //对用户输入的密码加密后 对比数据库的密码 并且用户的状态是正常的
            if (newPwd.equals(user.getPassword()) && user.getStatus().equals("0")) {
                //发放token令牌
                String token = TokenUtils.createToken(new TokenVo(user.getUserId() + "", user.getUserName(), newPwd));
                return new CommonResult<>(200, "success", token);
            } else {//密码错误 或者 账号封禁
                return new CommonResult<>(233, "账号密码错误,或用户状态异常");
            }
        } else {
            return new CommonResult<>(233, "用户不存在");
        }
    }

    /**
     * @param request
     * @return
     */
    @GetMapping("/checkToken")
    public CommonResult<TokenVo> checkToken(HttpServletRequest request) {
        log.info("执行了===>CommonController中的checkToken方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        if (tokenVo != null) {//有效token
            return new CommonResult<>(200, "success", tokenVo);
        } else {
            return new CommonResult<>(233, "token无效");
        }
    }

    @GetMapping("/logout")
    public CommonResult<String> logout() {
        log.info("执行了===>SysUserController中的logout方法");
        return new CommonResult<>(200, "退出成功");
    }

    @GetMapping("/getCurrentUser")
    public CommonResult<SysUser> getCurrentUser(HttpServletRequest request) {
        log.info("执行了===>CommonController中的getCurrentUser方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("user_name", tokenVo.getUserName()));
        return new CommonResult<>(200, "查询当前用户成功", user);
    }

    @PreAuthorize("@per.hasPermi('system:user:edit')")
    @PostMapping("/updateUser")
    public CommonResult<String> updateUser(@RequestBody SysUser user) throws NoSuchAlgorithmException {
        log.info("执行了===>SysUserController中的updateUser方法");
        if(ValidatorUtil.isUserName(user.getUserName())
                && (ValidatorUtil.isPassword(user.getPassword())||user.getPassword() == null || "".equals(user.getPassword()))
                && ValidatorUtil.isTrueName(user.getTrueName())
                && ValidatorUtil.isPhonenumber(user.getPhonenumber())
                && ValidatorUtil.isEmail(user.getEmail())
                && ValidatorUtil.isRemark(user.getRemark())){
        }else {
            return new CommonResult<>(233,"数据不合法");
        }
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if(user.getUserId()!=null&&!"".equals(user.getUserId())){
            wrapper = new QueryWrapper<SysUser>().eq("user_id", user.getUserId());
        }else {
            wrapper = new QueryWrapper<SysUser>().eq("user_name", user.getUserName());
        }
        // 查询当前用户信息
        SysUser userData = userService.getOne(wrapper);

        if (userData != null) {
            userData.setUpdateTime(new Date());
            userData.setTrueName(user.getTrueName());
            if(user.getPassword() != null && !user.getPassword().equals("")){
                //盐值
                String salt = UUID.randomUUID().toString().substring(0, 6);
                String newPwd = SaltEncryption.saltEncryption(user.getPassword(), salt);
                //设置加密
                userData.setPassword(newPwd);
                userData.setSalt(salt);
            }
            userData.setSex(user.getSex().equals("0")?"0":user.getSex().equals("1") ?"1":"2");
            userData.setPhonenumber(user.getPhonenumber());
            userData.setEmail(user.getEmail());
            userData.setStatus(user.getStatus().equals("0")?"0":"1");
            userData.setRemark(user.getRemark());

            boolean update = userService.update(userData, wrapper);
            return update ? new CommonResult<>(200, "更新用户信息成功") :
                    new CommonResult<>(233, "更新用户信息失败");
        }else {
            throw new RuntimeException("获取用户信息失败！");
        }
    }

    /**
     * @param userName  用户名
     * @param trueName  用户真实姓名
     * @param status    账号状态
     * @param dateRange 创建时间范围
     * @param pageNo    查询页数
     * @param pageSize  页面大小
     * @return
     * @throws InterruptedException
     */
    @PreAuthorize("@per.hasPermi('system:user:query')")
    @GetMapping("/getUser")
    public CommonResult<Object> getUser(@RequestParam(required = false) String userName,
                                        @RequestParam(required = false) String trueName,
                                        @RequestParam(required = false) String status,
                                        @RequestParam(required = false) String dateRange,
                                        Integer pageNo, Integer pageSize) throws InterruptedException {
        log.info("执行了===>SysUserController中的getUser方法");
        //参数一是当前页，参数二是每页个数
        IPage<SysUser> userPage = new Page<>(pageNo, pageSize);
        //查询条件(可选)
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (!Objects.equals(userName, "") && userName != null) {
            wrapper.like("user_name", userName);
        }
        if (!Objects.equals(trueName, "") && trueName != null) {
            wrapper.like("true_name", trueName);
        }
        if (!Objects.equals(status, "") && status != null) {
            wrapper.like("status", status);
        }
        if (!Objects.equals(dateRange, "") && dateRange != null) {
            wrapper.and(wrapper2 -> wrapper2.between("create_time",
                    dateRange.substring(0, dateRange.indexOf(",")),
                    dateRange.substring(dateRange.indexOf(",")+1)).or().isNull("create_time"));
        }
        userPage = userService.page(userPage, wrapper);
        List<SysUser> users = userPage.getRecords();
        // 创建分页结果集
        Map<Object, Object> result = new HashMap<>();
        result.put("users", users);
        result.put("total", userPage.getTotal());
        return new CommonResult<>(200, "success", result);
    }

    /**
     * @param userName 登录用户名
     * @return
     */
    @GetMapping(value = {"/check/{userName}","/check/"})
    public CommonResult<String> checkUserName(@PathVariable(value = "userName",required = false) String userName) {
        log.info("执行了===>SysUserController中的checkUserName方法");
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", userName);
            SysUser user = userService.getOne(wrapper);
            if (user == null) {
                return new CommonResult<>(200, "用户名可用");
            } else {
                return new CommonResult<>(233, "用户已存在");
            }
    }

    /**
     * @param user 用户实体
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PreAuthorize("@per.hasPermi('system:user:add')")
    @PostMapping("/addUser")
    public CommonResult<String> addUser(@RequestBody SysUser user) throws NoSuchAlgorithmException {
        log.info("执行了===>SystemController中的addUser方法");
        if(ValidatorUtil.isUserName(user.getUserName())
                && ValidatorUtil.isPassword(user.getPassword())
                && ValidatorUtil.isTrueName(user.getTrueName())
                && ValidatorUtil.isPhonenumber(user.getPhonenumber())
                && ValidatorUtil.isEmail(user.getEmail())
                && ValidatorUtil.isRemark(user.getRemark())){
        }else {
            return new CommonResult<>(233,"数据不合法");
        }
        //盐值
        String salt = UUID.randomUUID().toString().substring(0, 6);
        String newPwd = SaltEncryption.saltEncryption(user.getPassword(), salt);
        user.setPassword(newPwd);
        user.setSalt(salt);
        user.setSex(user.getSex().equals("0")?"0":user.getSex().equals("1") ?"1":"2");
        user.setStatus(user.getStatus().equals("0")?"0":"1");
        user.setCreateTime(new Date());
        boolean save = userService.save(user);
        return save ? new CommonResult<>(200, "操作成功") : new CommonResult<>(233, "操作失败");
    }

    /**
     * @param type    操作类型
     * @param userIds 操作用户的id的字符串,以逗号分隔
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/handleUser/{type}")
    public CommonResult<String> handleUser(@PathVariable("type") Integer type, String userIds) {
        log.info("执行了===>SysUserController中的handleUser方法");
        //转换成数组 需要操作的用户的id数组
        String[] ids = userIds.split(",");
        if (type == 1) {//启用
            if(!permissionService.hasPermi("system:user:statusOn")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                //当前需要修改的用户
                SysUser user = userService.getById(Integer.parseInt(id));
                user.setStatus("0");//设置为有效的用户
                userService.update(user, new UpdateWrapper<SysUser>().eq("user_id", Integer.parseInt(id)));
            }
            return new CommonResult<>(200, "操作成功");
        } else if (type == 2) {//禁用
            if(!permissionService.hasPermi("system:user:statusOff")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                //当前需要修改的用户
                SysUser user = userService.getById(Integer.parseInt(id));
                user.setStatus("1");//设置为无效的用户
                userService.update(user, new UpdateWrapper<SysUser>().eq("user_id", Integer.parseInt(id)));
            }
            return new CommonResult<>(200, "操作成功");
        } else if (type == 3) {//删除
            if(!permissionService.hasPermi("system:user:remove")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                userService.removeById(Long.parseLong(id));
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("user_id",id);
                userRoleService.remove(wrapper);
            }
            return new CommonResult<>(200, "操作成功");
        } else {
            return new CommonResult<>(233, "操作有误");
        }
    }

    @PreAuthorize("@per.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public CommonResult<String> importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        List<SysUser> userList = ExcelInsert.readExcel(file);
        String message = userService.importUser(userList, updateSupport);
        return new CommonResult<>(200, message);
    }

}

